<template>
  <div class="details-left">
    <div class="box-class">
      <span>{{ fileName }}</span>
      <!-- 下拉框 -->
      <Dropdown
        @send-new-files="createNewFile"
        @send-new-text="createNewText"
        @send-uploaded-files="createUploadFile"
      ></Dropdown>
    </div>
    <el-scrollbar height="600px" v-loading="loading">
      <div class="left-tree">
        <el-tree
          ref="treeRef"
          :data="fileListData"
          :props="defaultProps"
          @node-click="handleNodeClick"
          @current-change="handleNodeClick"
          highlight-current
          node-key="id"
        >
          <template #default="{ data }">
            <div class="box-list">
              <div class="file-name-icon">
                <div class="icon">
                  <svg class="action-icon" aria-hidden="true" width="20" height="20">
                    <use :xlink:href="getFileSvgIcon(data)" />
                  </svg>
                </div>
                <div class="file-name">
                  {{ data.fileName }}
                </div>
              </div>
              <!-- 下拉框 -->
              <Dropdown
                :fileData="data"
                @send-new-text="createNewText(data)"
                @send-new-files="createNewFile"
                @send-uploaded-files="createUploadFile"
                @send-new-children="createNewChildrenFile(data)"
                @send-rename="handleRename(data)"
                @send-delete="hadleDelete(data)"
                @send-up-children-file="createChildrenUploadFile(data)"
              ></Dropdown>
            </div>
          </template>
        </el-tree>
      </div>
    </el-scrollbar>

    <!-- 重命名/新建弹出框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitile"
      width="430px"
      min-width="430px"
      :before-close="handleClose"
    >
      <AddDialog
        :formData="formData"
        :dialogTitile="dialogTitile"
        @send-close-dialog="handleClose"
        @send-submit-dialog="handleSubmitAdd"
      ></AddDialog>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, defineExpose, watch, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox, ElTree } from 'element-plus'

// import { getPageList, deletePageData, newPageData, editPageData } from '@/apis/system/doc-center'
import { store } from '@/store/doc-center'
import { storeToRefs } from 'pinia'
import {
  editDocumentData,
  deleteDocumentData,
  getDocumentList,
  newDocumentData,
  newDocData,
  getDocList,
  deleteDocData
} from '@/apis/system/document'

import Dropdown from './Dropdown.vue'
import AddDialog from './AddDialog.vue'
import { number } from 'echarts'
import { IfileListData } from '../../config/fileListData'
import { newRecordData } from '@/apis/system/docRecord'

// import { setRecordAdd } from '@/apis/system/setFilesRecord'

const docStore = store()
const { docListData } = storeToRefs(docStore)
const formData = ref({
  attachments: [],
  cover: [],
  fileName: '',
  newFileName: '',
  id: 0,
  filename: ''
})

const props = defineProps({
  breadListNode: {
    type: Number,
    default: null
  }
})

watch(
  () => props.breadListNode,
  (newVal) => {
    if (newVal) {
      treeRef.value?.setCurrentKey(newVal)
    }
  },
  { immediate: true }
)

/**
 *
 * @desc:获取登录用户信息
 */
const getUserInfo = computed(() => {
  return JSON.parse(localStorage.getItem('user') as string) || ''
})

const defaultProps = {
  label: 'fileName',
  children: 'children_data'
}

/**
 * @desc: 点击进入详情页获取标题
 */
const $router = useRouter()
const fileName = ref($router.currentRoute.value.query.name as string)
const parentId = ref(+$router.currentRoute.value.query.parent_id!)
const treeRef = ref<InstanceType<typeof ElTree>>()


/**
 * @desc: 通过子级获取父级数据
 * @param {*} itemId
 * @param {*} treeList
 * @return {*}
 */
const getParentPath = (itemId: number, treeList: IfileListData[]) => {
  for (let i = 0; i < treeList.length; i++) {
    const { id, children_file = [] } = treeList[i]
    if (+itemId === +id) {
      return [treeList[i]]
    }
    if (children_file && children_file.length) {
      let result: any = getParentPath(itemId, children_file)
      if (result) {
        return result.concat(treeList[i])
      }
    }
  }
  return null
}

/**
 * @desc: 获取左侧树
 */
const fileListData = ref<IfileListData[]>()
const loading = ref(false)
const getData = (newFileId?: number) => {
  loading.value = true
  getDocumentList({
    id: parentId.value
  }).then((res) => {
    if (!res) return
    fileName.value = res[0]?.fileName
    fileListData.value = res[0]?.children_file
    docListData.value = res[0]?.children_file
    loading.value = false
    // 外部点击进来的文件
    if (!!$router.currentRoute.value.query.file_id) {
      const fileId = +$router.currentRoute.value.query.file_id!
      nextTick(() => {
        treeRef.value?.setCurrentKey(fileId)
      })
      // 获取所有父级数据/渲染面包屑
      const allParentsData = getParentPath(fileId, fileListData.value as IfileListData[])
      let breadListArr: object[] = []
      allParentsData.map((item: IfileListData) => {
        breadListArr.unshift({ fileName: item.fileName, id: item.id })
      })
      emit('send-breadList-arr', breadListArr)
    }
    if (newFileId) {
      nextTick(() => {
        treeRef.value?.setCurrentKey(newFileId)
      })
    }
  })
}

getData()

/**
 * @desc: 上传成功后的回调
 */
// interface Ires {
//   originalname: string
// }
const API_BASE_URL = 'http://localhost:3008'
const createUploadFile = (data: any) => {
  let filePathUrl = data?.path.split('\\')
  let params = {}
  if (childrenId.value) {
    params = {
      parent_id: childrenId.value,
      fileName: data?.originalname.split('.')[0],
      filesize: data.size,
      filetype: data.originalname.split('.')[1],
      user_id: getUserInfo.value.id,
      user_name: getUserInfo.value.userName,
      filepath: API_BASE_URL + '/' + filePathUrl[0] + '/' + filePathUrl[1],
      top_parent_id: parentId.value
    }
  } else {
    params = {
      parent_id: parentId.value,
      top_parent_id: parentId.value,
      fileName: data?.originalname.split('.')[0],
      filesize: data.size,
      filetype: data.originalname.split('.')[1],
      user_id: getUserInfo.value.id,
      user_name: getUserInfo.value.userName,
      filepath: API_BASE_URL + '/' + filePathUrl[0] + '/' + filePathUrl[1]
    }
  }
  newDocData(params)
    .then((res) => {
      if (!res) return
      setRecordAdd(
        res._id,
        data?.originalname.split('.')[0],
        data.originalname.split('.')[1],
        +parentId.value!,
        getUserInfo.value,
        API_BASE_URL + '/' + filePathUrl[0] + '/' + filePathUrl[1]
      )
      getData()
    })
    .catch((res) => {
      ElMessage('服务器内部错误@@')
    })
}

const setRecordAdd = (
  id: number,
  name: string,
  fileType: string,
  topParentId: number,
  userInfo: { userName: string; id: number },
  fileUrl?: string
) => {
  let params = {
    operation: 'add',
    top_parent_id: topParentId,
    user_name: userInfo.userName,
    user_id: userInfo.id,
    fileName: name,
    page_id: id,
    type: fileType,
    url: fileUrl,
    parent_id: parentId.value
  }
  newRecordData(params).then((res) => {
    if (!res) return
  })
}

const fileTypeHash: { [key: string]: string } = {
  bmp: '#iconzhaopian1x',
  jpg: '#iconzhaopian1x',
  png: '#iconzhaopian1x',
  gif: '#iconzhaopian1x',
  jpeg: '#iconzhaopian1x',
  cdr: '#iconzhaopian1x',
  psd: '#iconzhaopian1x',
  doc: '#iconword1x',
  docx: '#iconword1x',
  pdf: '#iconpdf1x',
  ppt: '#iconppt1x',
  pptx: '#iconppt1x',
  xlsx: '#iconexcle1x',
  xls: '#iconexcle1x',
  txt: '#icontxt1x',
  mp3: '#iconyinle',
  wav: '#iconyinle',
  mp4: '#iconzhihuigongdi',
  webm: '#iconzhihuigongdi',
  ogg: '#iconzhihuigongdi',
  folder: '#iconwenjianjia1'
}

const getFileSvgIcon = (data: { type: string; filepath: string }) => {
  let last = null
  if (!data.filepath) {
    last = data.type
  } else {
    let arr = data.filepath.split('.')
    last = arr[arr.length - 1].toLocaleLowerCase()
  }
  return fileTypeHash[last] || '#iconother1x' // 为解决：找不到具有类型为 "string" 的参数的索引签名
}

/**
 * @desc: 新建文本文档
 */
const createNewText = (data: { id: number }) => {
  if (data && data.id) {
    childrenId.value = data.id
  }
  formData.value.newFileName = ''
  dialogTitile.value = '新建文本文档'
  dialogVisible.value = true
}

/**
 * @desc: 新建文件夹
 */
const createNewFile = () => {
  formData.value.newFileName = ''
  dialogTitile.value = '新建文件夹'
  dialogVisible.value = true
}

/**
 * @desc: 新建子文件夹
 */
const childrenId = ref<number>()
const createNewChildrenFile = (data: { id: number }) => {
  childrenId.value = data.id
  dialogTitile.value = '新建子文件夹'
  dialogVisible.value = true
}

/**
 * @desc: 上传子文件
 */
const createChildrenUploadFile = (data: { id: number }) => {
  childrenId.value = data.id
}

/**
 * @desc: 点击文件在右侧显示
 */
const emit = defineEmits(['send-click-node', 'send-breadList-arr'])
const handleNodeClick = (item: object, node: { id: number }) => {
  emit('send-click-node', item, node)
}

/**
 * @desc: 重命名
 */
let dialogTitile = ref<string>()
const dialogVisible = ref(false)
const handleRename = (item: { fileName: string; id: number }) => {
  formData.value.fileName = item.fileName
  formData.value.id = item.id
  dialogTitile.value = '重命名'
  dialogVisible.value = true
}

/**
 * @desc: 删除
 */
const hadleDelete = (item: { fileName: string; id: number }) => {
  ElMessageBox.confirm(`是否删除文件 ${item.fileName}?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  })
    .then(() => {
      deleteDocData(item.id)
        .then((res) => {
          if (!res) return
          getData()
        })
        .catch((res) => {
          ElMessage('服务器内部错误')
        })
      ElMessage({
        type: 'success',
        message: '删除成功'
      })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '已取消'
      })
    })
}

/**
 * @desc: 保存提交
 *
 */
let params = {
  parent_id: 0,
  top_parent_id: 0,
  fileName: '',
  filetype: '',
  user_id: 0,
  user_name: ''
}
const ruleFormRef = ref()
const handleSubmitAdd = () => {
  switch (dialogTitile.value) {
    case '重命名':
      // editPageData(formData.value, formData.value.id)
      //   .then((res) => {
      //     setRecordEdit(res.data, +parentId.value!, getUserInfo.value)
      //     getData(res.data.id)
      //     ElMessage({
      //       type: 'success',
      //       message: res.msg
      //     })
      //   })
      //   .catch((res) => {
      //     ElMessage('服务器内部错误')
      //   })
      break
    case '新建文本文档':
      if (childrenId.value) {
        params.parent_id = childrenId.value
        params.top_parent_id = parentId.value
        params.fileName = formData.value.newFileName
        params.filetype = 'txt'
        params.user_id = getUserInfo.value.id
        params.user_name = getUserInfo.value.userName
      } else {
        params.parent_id = parentId.value
        params.top_parent_id = parentId.value
        params.fileName = formData.value.newFileName
        params.filetype = 'txt'
        params.user_id = getUserInfo.value.id
        params.user_name = getUserInfo.value.userName
      }
      newDocData(params)
        .then((res) => {
          if (!res) return
          setRecordAdd(res._id, params.fileName, 'txt', params.top_parent_id, getUserInfo.value)
          getChildrenData(res._id)
          getData(res._id)
          ElMessage({
            type: 'success',
            message: '创建成功'
          })
        })
        .catch((res) => {
          ElMessage('服务器内部错误')
        })
      break
    case '新建文件夹':
      params = {
        parent_id: parentId.value,
        top_parent_id: parentId.value,
        fileName: formData.value.newFileName,
        type: 'folder',
        url: 'folder'
      }
      // newPageData(params)
      //   .then((res: { code: number; data: { id: number|undefined } }) => {
      //     if (res.code !== 200) return
      //     // setRecordAdd(res.data, +parentId.value!, getUserInfo.value)
      //     getData(res.data.id)
      //     ElMessage({
      //       type: 'success',
      //       message: '创建成功'
      //     })
      //   })
      //   .catch((res: any) => {
      //     ElMessage('服务器内部错误')
      //   })
      break
    case '新建子文件夹':
      let childrenParams = {
        parent_id: childrenId.value,
        top_parent_id: parentId.value,
        fileName: formData.value.newFileName,
        type: 'folder',
        url: 'folder'
      }
      // newPageData(childrenParams)
      //   .then((res: { code: number; data: { id: number|undefined } }) => {
      //     if (res.code !== 200) return
      //     // setRecordAdd(res.data, +parentId.value!, getUserInfo.value)
      //     getData(res.data.id)
      //     ElMessage({
      //       type: 'success',
      //       message: '创建成功'
      //     })
      //   })
      //   .catch((res: any) => {
      //     ElMessage('服务器内部错误')
      //   })
      break
  }
  dialogVisible.value = false
}

/**
 * @desc: 获取文件夹子文件
 */
const folderChilderData = ref<IfileListData[]>()
const getChildrenData = (newFileId?: number) => {
  loading.value = true
  getDocList(newFileId).then((res) => {
    if (!res) return
    $router.push({
      name: 'DocRichEditor',
      query: { id: res.id, fileName: res.fileName }
    })
    loading.value = false
  })
}

/**
 * @desc: 取消提交
 *
 */
const handleClose = () => {
  formData.value.newFileName = ''
  dialogVisible.value = false
}

defineExpose({ getData })
</script>

<style lang="less" scoped>
.details-left {
  overflow: hidden;
  .box-class {
    display: flex;
    justify-content: space-between;
    height: 40px;
    padding-left: 10px;
    line-height: 40px;
    span {
      flex-grow: 1;
      width: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
      font-size: 18px;
      font-weight: 600;
      text-align: left;
    }
  }
  .left-tree {
    :deep(.el-tree-node__expand-icon) {
      font-size: 18px;
    }
    :deep(.el-tree-node__content) {
      width: 100%;
      height: 40px;
      box-sizing: border-box;
    }
    :deep(.el-tree-node__label) {
      width: 100%;
    }
    :deep(.el-tree-node:focus > .el-tree-node__content) {
      color: #409eff;
    }

    .box-list {
      width: 100%;
      display: flex;
      justify-content: space-between;
      height: 40px;
      align-items: center;
      .drop-down-main {
        opacity: 0;
      }
      &:hover .drop-down-main {
        opacity: 1;
      }

      .title {
        padding-left: 10px;
      }
      .file-name-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        .icon {
          width: 30px;
        }
        .file-name {
          width: 100px;
          line-height: 19px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }
}
</style>
